/// 存储服务类
/// 处理本地数据存储，如令牌、用户信息等
library;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:chat_project/models/user_model.dart';

/// 存储服务
/// 用于在本地存储数据和管理存储状态
class StorageService {
  // SharedPreferences 键
  static const String _isLoggedInKey = 'isLoggedIn';
  static const String _userKey = 'user';
  static const String _tokenKey = 'token';
  static const String _settingsKey = 'settings';
  
  // 检查用户是否已登录
  Future<bool> isLoggedIn() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_isLoggedInKey) ?? false;
  }
  
  // 设置登录状态
  Future<void> setLoggedIn(bool value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_isLoggedInKey, value);
  }
  
  // 保存用户信息
  Future<void> saveUser(User user) async {
    final prefs = await SharedPreferences.getInstance();
    final userJson = json.encode(user.toJson());
    await prefs.setString(_userKey, userJson);
  }
  
  // 获取用户信息
  Future<User?> getUser() async {
    final prefs = await SharedPreferences.getInstance();
    final userJson = prefs.getString(_userKey);
    
    if (userJson == null) return null;
    
    try {
      final userData = json.decode(userJson) as Map<String, dynamic>;
      return User.fromJson(userData);
    } catch (e) {
      // 如果解析失败，返回null
      return null;
    }
  }
  
  // 保存令牌
  Future<void> saveToken(String token) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, token);
  }
  
  // 获取令牌
  Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_tokenKey);
  }
  
  // 保存设置
  Future<void> saveSettings(Map<String, dynamic> settings) async {
    final prefs = await SharedPreferences.getInstance();
    final settingsJson = json.encode(settings);
    await prefs.setString(_settingsKey, settingsJson);
  }
  
  // 获取设置
  Future<Map<String, dynamic>?> getSettings() async {
    final prefs = await SharedPreferences.getInstance();
    final settingsJson = prefs.getString(_settingsKey);
    
    if (settingsJson == null) return null;
    
    try {
      return json.decode(settingsJson) as Map<String, dynamic>;
    } catch (e) {
      // 如果解析失败，返回null
      return null;
    }
  }
  
  // 清除所有数据
  Future<void> clearAll() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_isLoggedInKey);
    await prefs.remove(_userKey);
    await prefs.remove(_tokenKey);
    // 如果需要保留设置，则不要清除设置
    // await prefs.remove(_settingsKey);
  }
} 